package priv.books.controller;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import priv.books.pojo.Books;
import priv.books.pojo.ResultMessage;
import priv.books.service.BooksService;
import priv.books.service.BooksTypeService;

/**
 * 书籍类型控制器
 */
@RestController
@RequestMapping("/books")
public class BooksController {

    @Autowired
    private BooksService booksService;

    /**
     * 修改信息
     * @param books
     * @return
     */
    @PostMapping("/updateInfo")
    public ResultMessage updateInfo(Books books) {
        try {
            // 调用service 修改方法
            boolean result = booksService.updateInfo(books);
            if(result) {
                return new ResultMessage(0, "操作成功！");
            }
            return new ResultMessage(207, "操作无响应！");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMessage(500, "出现异常：" + e.getMessage());
        }
    }

    /**
     * 新增信息
     * @param books
     * @return
     */
    @PostMapping("/insertInfo")
    public ResultMessage insertInfo(Books books) {
        try {
            // 设置销量
            books.setSalesVolume(0);
            // 调用service 修改方法
            boolean result = booksService.save(books);
            if(result) {
                return new ResultMessage(0, "操作成功！");
            }
            return new ResultMessage(207, "操作无响应！");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMessage(500, "出现异常：" + e.getMessage());
        }
    }

    /**
     * 删除信息
     * @param id
     * @return
     */
    @DeleteMapping("/deleteInfo")
    public ResultMessage deleteInfo(Integer id, String ids) {
        try {
            // 调用service 修改方法
            boolean result = false;
            if(id != null && id != 0) {
                result = booksService.remove(new QueryWrapper<Books>().eq("id", id));
            } else if(!StrUtil.isBlankOrUndefined(ids)) {
                result = booksService.removeByIds(StrUtil.split(ids, ',', true, true));
            }
            if(result) {
                return new ResultMessage(0, "操作成功！");
            }
            return new ResultMessage(207, "操作无响应！");
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultMessage(500, "出现异常：" + e.getMessage());
        }
    }

}
